package com.iemes.controller.work_process;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.iemes.controller.index.BaseController;
import com.iemes.entity.FlowStepFormMap;
import com.iemes.entity.ItemFormMap;
import com.iemes.entity.NcCodeFormMap;
import com.iemes.entity.NcCodeGroupFormMap;
import com.iemes.entity.NcRepairFormMap;
import com.iemes.entity.OperationFormMap;
import com.iemes.entity.PodPanelFormMap;
import com.iemes.entity.SfcAssemblyFormMap;
import com.iemes.entity.SfcNcFormMap;
import com.iemes.entity.SfcStepFormMap;
import com.iemes.entity.ShopOrderSfcFormMap;
import com.iemes.entity.ShoporderFormMap;
import com.iemes.entity.WorkCenterFormMap;
import com.iemes.entity.WorkResourceFormMap;
import com.iemes.exception.BusinessException;
import com.iemes.service.CommonService;
import com.iemes.service.work_process.WorkPodPanelService;
import com.iemes.util.Common;
import com.iemes.util.DateUtils;
import com.iemes.util.ListUtils;
import com.iemes.util.ResponseHelp;
import com.iemes.util.ShiroSecurityHelper;
import com.iemes.util.UUIDUtils;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/work_process/work_pod_panel/")
public class WorkPodPanelController extends BaseController {

	private Logger log = Logger.getLogger(this.getClass());
	
	@Inject
	private WorkPodPanelService workPodPanelService;
	
	@Inject
	private CommonService commonService;
	
	//POD工作主界面
	private final String workPodPanelMaintenanceUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/work_pod_panel_maintenance";
	
	//选择下一步操作界面
	private final String checkNextOperationUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/check_next_operation";
	
	//装配物料清单界面
	private final String assembleItemListUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/pod_assemble_list";
	
	//装配界面
	private final String assembleUIUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/pod_assemble_maintenance";
	
	//选择绑定工单界面
	private final String checkBindShororderUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/check_bind_shoporder";
	
	//记录不良界面
	private final String recordNcCodeUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/pod_record_nocode_maintenance";
	
	//报废界面
	private final String scrapUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/pod_scrap_maintenance";
	
	//维修界面
	private final String repairUrl = Common.BACKGROUND_PATH + "/work_process/pod_opeartion/pod_repair_maintenance";
	
	/**
	 * 进入POD工作面板界面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("work_pod_panel_maintenance")
	public String work_pod_panel_maintenance(Model model, HttpServletRequest request) {
		try {
			String id = request.getParameter("id");
			getPodPanelInfo(model, request, id);
		}catch(BusinessException e) {
			log.error(e.getMessage(), e);
			model.addAttribute("errorMessage", e.getMessage());
			return workPodPanelMaintenanceUrl;
		}
		return workPodPanelMaintenanceUrl;
	}
	
	/**
	 * 查询POD工作面板相关信息
	 * @param model
	 * @param request
	 * @param podPanelId
	 */
	private void getPodPanelInfo(Model model, HttpServletRequest request, String podPanelId) {
		List<PodPanelFormMap> listPodPanelFormMap = baseMapper.findByAttribute("id", podPanelId, PodPanelFormMap.class);
		PodPanelFormMap podPanelFormMap = listPodPanelFormMap.get(0);
		
		String operation_id = request.getParameter("operation_id");
		String resource_id = request.getParameter("resource_id");
		
		//查询默认操作NO
		String operationId = podPanelFormMap.getStr("default_operation");
		if (!StringUtils.isEmpty(operation_id)) operationId = operation_id;
		
		if (!StringUtils.isEmpty(operationId)) {
			List<OperationFormMap> listOperationFormMap = baseMapper.findByAttribute("id", operationId, OperationFormMap.class);
			if (ListUtils.isNotNull(listOperationFormMap)) {
				OperationFormMap operationFormMap = listOperationFormMap.get(0);
				String operationNo = operationFormMap.getStr("operation_no");
				model.addAttribute("operationNo", operationNo);
			}
		}
		
		//查询默认资源NO
		String workResourceId = podPanelFormMap.getStr("default_resource");
		if (!StringUtils.isEmpty(resource_id)) workResourceId = resource_id;
		
		if (!StringUtils.isEmpty(workResourceId)) {
			List<WorkResourceFormMap> listWorkResourceFormMap = baseMapper.findByAttribute("id", workResourceId, WorkResourceFormMap.class);
			if (ListUtils.isNotNull(listWorkResourceFormMap)) {
				WorkResourceFormMap workResourceFormMap = listWorkResourceFormMap.get(0);
				String workResourceNo = workResourceFormMap.getStr("resource_no");
				model.addAttribute("workResourceNo", workResourceNo);
			}
		}
		
		//查询面板按钮
		List<Map<String, String>> listButton = workPodPanelService.getButtonsByPodPanel(podPanelId);
		model.addAttribute("listButton", listButton);
		
		//查询当前操作上正在生产的SFC列表
		if (!StringUtils.isEmpty(operationId)) {
			List<Map<String, String>> sfcList = workPodPanelService.getSfcOnOperation(operationId);
			model.addAttribute("sfcList", sfcList);
		}
		model.addAttribute("operationId", operationId);
		model.addAttribute("workResourceId", workResourceId);
		model.addAttribute("successMessage", ShiroSecurityHelper.getSession().getAttribute("successMessage"));
		ShiroSecurityHelper.getSession().removeAttribute("successMessage");
		model.addAttribute("id", podPanelId);
	}
	
	/**
	 * 查询当前操作上的SFC列表
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("getSfcOnOperation")
	public String getSfcOnOperation(Model model, HttpServletRequest request) {
		String podPanelId = request.getParameter("podPanelId");
		String operationId = request.getParameter("operation_id");
		String workResourceId = request.getParameter("workResource_id");
		
		String workResourceNo = request.getParameter("workResource_no");
		String operationNo = request.getParameter("operation_no");
		try {
			getPodPanelInfo(model, request, podPanelId);
			model.addAttribute("workResourceNo", workResourceNo);
			model.addAttribute("operationNo", operationNo);
			model.addAttribute("operationId", operationId);
			model.addAttribute("workResourceId", workResourceId);
			List<Map<String, String>> sfcList = workPodPanelService.getSfcOnOperation(operationId);
			model.addAttribute("sfcList", sfcList);
			return workPodPanelMaintenanceUrl;
		}catch(BusinessException e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			getPodPanelInfo(model, request, podPanelId);
			model.addAttribute("errorMessage", e.getMessage());
			return workPodPanelMaintenanceUrl;
		}
	}
	
	@ResponseBody
	@RequestMapping("getWorkLineByResource")
	public String getWorkLineByResource(Model model, HttpServletRequest request) {
		String workResource_id = request.getParameter("workResource_id");
		List<WorkResourceFormMap> listWorkResourceFormMap = baseMapper.findByAttribute("id", workResource_id, WorkResourceFormMap.class);
		if (!ListUtils.isNotNull(listWorkResourceFormMap)) {
			String msg = "资源编号有误，未能根据资源查找到相关资源信息";
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		WorkResourceFormMap workResourceFormMap = listWorkResourceFormMap.get(0);
		String workline_id = workResourceFormMap.getStr("workline_id");
		if (StringUtils.isEmpty(workline_id)) {
			String msg = "资源："+workResourceFormMap.getStr("resource_no") + "的所属工作中心字段不能为空，请先维护所属工作中心！！！";
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	@ResponseBody
	@RequestMapping("podStart")
	public String podStart(Model model, HttpServletRequest request) {
		try {
			String sfc = request.getParameter("sfc");
			String operationId = request.getParameter("operation_id");
			String operation_no = request.getParameter("operation_no");
			String resourceId = request.getParameter("resource_id");
			
			//0、判断SFC在不在shoporder_sfc有中
			ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
			shopOrderSfcFormMap.put("sfc", sfc);
			shopOrderSfcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByNames(shopOrderSfcFormMap);
			if (!ListUtils.isNotNull(listShopOrderSfcFormMap)) {
				String msg = "SFC不存在，未能检索到相关的SFC信息";
				log.error(msg);
				return ResponseHelp.responseErrorText(msg);
			}
			
			//1、判断SFC当前状态是不是为创建、生产中、维修
			ShopOrderSfcFormMap shopOrderSfcFormMap2 = listShopOrderSfcFormMap.get(0);
			int sfcStatus = shopOrderSfcFormMap2.getInt("sfc_status");
			if (sfcStatus != 0 && sfcStatus != 1 && sfcStatus != 4) {
				String msg = "该SFC不在该操作上排队，请使用正确的SFC进行操作";
				log.error(msg);
				return ResponseHelp.responseErrorText(msg);
			}
			
			//2、判断工单状态是否可以执行操作
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByAttribute("id", shopOrderSfcFormMap2.getStr("shoporder_id"), ShoporderFormMap.class);
			ShoporderFormMap shoporderFormMap = listShoporderFormMap.get(0);
			int shopOrderStatus = shoporderFormMap.getInt("status");
			String shopOrderStatusStr = commonService.getShoporderStatusStr(shopOrderStatus);
			if (shopOrderStatus==3 || shopOrderStatus==4 || shopOrderStatus==5) {
				String msg = "当前工单状态为："+shopOrderStatusStr+", 不允许进行记录不合格操作";
				log.error(msg);
				throw new BusinessException(msg);
			}

			//3、是否在sfc_step表中查找到记录
			SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
			sfcStepFormMap.put("sfc", sfc);
			sfcStepFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcStepFormMap.put("orderby", " order by seq desc");
			List<SfcStepFormMap> listSfcStepFormMap = baseMapper.findByNames(sfcStepFormMap);
			if (!ListUtils.isNotNull(listSfcStepFormMap)) {
				String msg = "未找到相关的SFC：" + sfc + "的步骤信息";
				log.error(msg);
				return ResponseHelp.responseErrorText(msg);
			}
			SfcStepFormMap sfcStepFormMap2 = listSfcStepFormMap.get(0);
			Integer status = sfcStepFormMap2.getInt("status");
			String operationId2 = sfcStepFormMap2.getStr("operation_id");
			if (!operationId.equals(operationId2)) {
				String msg = "sfc不在当前操作上作业";
				log.error(msg);
				return ResponseHelp.responseErrorText(msg);
			}
			if (status != 0) {
				String sfcStepStatus = commonService.getSfcStepStatusStr(status);
				String msg = "sfc状态为" + sfcStepStatus + ",不允许执行开始操作";
				log.error(msg);
				return ResponseHelp.responseErrorText(msg);
			}
			
			sfcStepFormMap2.put("finish_time", DateUtils.getStringDateTime());
			sfcStepFormMap2.put("work_resource_id", resourceId);
			
			// 查询是否为首操作
			FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
			flowStepFormMap.put("operation_id", operationId);
			flowStepFormMap.put("process_workflow_id", sfcStepFormMap2.getStr("process_workflow_id"));
			flowStepFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			flowStepFormMap.put("status", 1);
			List<FlowStepFormMap> list = baseMapper.findByNames(flowStepFormMap);
			
			shopOrderSfcFormMap2.put("sfc_status", 1);
			if (!ListUtils.isNotNull(list)) {
				shopOrderSfcFormMap2 = null;
			}
			
			// 追加一条记录
			SfcStepFormMap sfcStepFormMap3 = new SfcStepFormMap();
			sfcStepFormMap3.putAll(sfcStepFormMap2);
			sfcStepFormMap3.remove("seq");
			sfcStepFormMap3.put("id", UUIDUtils.getUUID());
			sfcStepFormMap3.put("status", 1);
			sfcStepFormMap3.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcStepFormMap3.put("create_time", DateUtils.getStringDateTime());
			
			workPodPanelService.podStart(sfcStepFormMap2, sfcStepFormMap3, shopOrderSfcFormMap2);
			ShiroSecurityHelper.getSession().setAttribute("successMessage", "SFC已经在操作："+operation_no+"上开始作业");
		} catch (Exception e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 获取下一个操作
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getNextOperation")
	public String getNextOperation(Model model, HttpServletRequest request) {
		String data = request.getParameter("data");
		ShiroSecurityHelper.getSession().removeAttribute("finishData");
		ShiroSecurityHelper.getSession().setAttribute("finishData", data);
		
		JSONObject jsonObj = JSONObject.fromObject(data);
		String process_workflow_id = jsonObj.getString("process_workflow_id");
		try {
			List<FlowStepFormMap> nextOperation = commonService.getNextOperation(jsonObj.getString("operation_id"), process_workflow_id);
			ShiroSecurityHelper.getSession().setAttribute("nextOperation", nextOperation);
			return ResponseHelp.responseListToText(nextOperation);
		}catch(BusinessException e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
	}
	
	/**
	 * 选择下一个操作
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("checkNextOperation")
	public String checkNextOperation(Model model, HttpServletRequest request) {
		List<FlowStepFormMap> dataList = (List<FlowStepFormMap>) ShiroSecurityHelper.getSession().getAttribute("nextOperation");
		ShiroSecurityHelper.getSession().removeAttribute("nextOperation");
		for (int i=0; i<dataList.size(); i++) {
			FlowStepFormMap object = dataList.get(i);
			String nextOperationId = object.getStr("next_operation_id");
			List<OperationFormMap> listOperationFormMap = baseMapper.findByAttribute("id", nextOperationId, OperationFormMap.class);
			OperationFormMap operationFormMap = listOperationFormMap.get(0);
			object.put("next_operation_no", operationFormMap.getStr("operation_no"));
		}
		model.addAttribute("dataList", dataList);
		return checkNextOperationUrl;
	}

	/**
	 * 选择要绑定的工单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("checkBindShoporder")
	public String checkBindShoporder(Model model, HttpServletRequest request) {
		ShoporderFormMap shoporderFormMap = new ShoporderFormMap();
		String siteId = ShiroSecurityHelper.getSiteId();
		shoporderFormMap.put("where"," where site_id ='" + siteId +"' and is_sfc_auto_generate = -1 and (status = 1 or status = 2)");
		List<ShoporderFormMap> dataList = baseMapper.findByWhere(shoporderFormMap);
		model.addAttribute("dataList", dataList);
		return checkBindShororderUrl;
	}
	
	@ResponseBody
	@RequestMapping("checkShopOrderStatus")
	public String checkShopOrderStatus(Model model, HttpServletRequest request) {
		String dataString = (String) ShiroSecurityHelper.getSession().getAttribute("assembleList");
		JSONObject dataObj = JSONObject.fromObject(dataString);
		String shoporder_id = dataObj.getString("shoporder_id");
		//判断工单状态是否可以执行操作
		List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByAttribute("id", shoporder_id, ShoporderFormMap.class);
		ShoporderFormMap shoporderFormMap = listShoporderFormMap.get(0);
		int shopOrderStatus = shoporderFormMap.getInt("status");
		String shopOrderStatusStr = commonService.getShoporderStatusStr(shopOrderStatus);
		if (shopOrderStatus==3 || shopOrderStatus==4 || shopOrderStatus==5) {
			String msg = "当前工单状态为："+shopOrderStatusStr+", 不允许进行记录不合格操作";
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 执行POD完成功能
	 * 
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("podFinish")
	public String podFinish(Model model, HttpServletRequest request) {
		try {
			List<FlowStepFormMap> dataList = (List<FlowStepFormMap>) ShiroSecurityHelper.getSession().getAttribute("nextOperation");
			String data = ShiroSecurityHelper.getSession().getAttribute("finishData").toString();
			String next_operation_id = request.getParameter("next_operation_id");

			ShiroSecurityHelper.getSession().removeAttribute("finishData");
			ShiroSecurityHelper.getSession().removeAttribute("nextOperation");

			JSONObject fromObject = JSONObject.fromObject(data);
			
			//判断工单状态是否可以执行操作
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByAttribute("id", fromObject.getString("shoporder_id"), ShoporderFormMap.class);
			ShoporderFormMap shoporderFormMap = listShoporderFormMap.get(0);
			int shopOrderStatus = shoporderFormMap.getInt("status");
			String shopOrderStatusStr = commonService.getShoporderStatusStr(shopOrderStatus);
			if (shopOrderStatus==3 || shopOrderStatus==4 || shopOrderStatus==5) {
				String msg = "当前工单状态为："+shopOrderStatusStr+", 不允许进行完成操作";
				log.error(msg);
				throw new BusinessException(msg);
			}

			workPodPanelService.podFinish(fromObject, next_operation_id);
			ShiroSecurityHelper.getSession().setAttribute("successMessage", "SFC已经在操作："+fromObject.getString("operation_no")+"上完成作业");
		} catch (BusinessException e) {
			e.printStackTrace();
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 获得装配物料清单
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("getAssembleItemBom")
	public String getAssembleItemBom(Model model, HttpServletRequest request) {
		
		String dataString = (String) ShiroSecurityHelper.getSession().getAttribute("assembleList");
		ShiroSecurityHelper.getSession().removeAttribute("assembleList");
		JSONObject dataObj = JSONObject.fromObject(dataString);
		
		String itemId = dataObj.getString("item_id");
		String sfc = dataObj.getString("sfc");
		String workshop_no = dataObj.getString("workshop");
		String workline_no = dataObj.getString("workline");
		String operation_no = dataObj.getString("operation_no");
		String work_resource_no = dataObj.getString("resource_no");
		String shoporder_no = dataObj.getString("shoporder");
		
		String workshop_id = dataObj.getString("workshop_id");
		String workline_id = dataObj.getString("workline_id");
		String operation_id = dataObj.getString("operation_id");
		String work_resource_id = dataObj.getString("work_resource_id");
		String shoporder_id = dataObj.getString("shoporder_id");
		
		
		Map<String, String> param = new HashMap<String, String>();
		param.put("itemId", itemId);
		param.put("sfc", sfc);
		param.put("workshop_no", workshop_no);
		param.put("workline_no", workline_no);
		param.put("operation_no", operation_no);
		param.put("work_resource_no", work_resource_no);
		param.put("shoporder_no", shoporder_no);
		
		param.put("workshop_id", workshop_id);
		param.put("workline_id", workline_id);
		param.put("operation_id", operation_id);
		param.put("work_resource_id", work_resource_id);
		param.put("shoporder_id", shoporder_id);
		
		List<Map<String, Object>> dataList = workPodPanelService.getAssembleList(param);
		model.addAttribute("dataList", dataList);
		return assembleItemListUrl;
	}
	
	/**
	 * 装配界面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("assemble_ui")
	public String assemble_ui(Model model, HttpServletRequest request) {
		
		String dataString = (String) ShiroSecurityHelper.getSession().getAttribute("assemble");
		ShiroSecurityHelper.getSession().removeAttribute("assemble");
		JSONObject dataObj = JSONObject.fromObject(dataString);
		String item_id = dataObj.getString("item_sfc_id");
		List<ItemFormMap> list = baseMapper.findByAttribute("id", item_id, ItemFormMap.class);
		if (!ListUtils.isNotNull(list)) {
			model.addAttribute("errorMessage", "未能查询到相关的物料信息，请确认该物料是否被删除");
			return assembleUIUrl;
		}
		ItemFormMap itemFormMap = list.get(0);
		String item_save_type = itemFormMap.getStr("item_save_type");
		model.addAttribute("item_save_type", item_save_type);
		model.addAttribute("assembleMap", dataObj);
		return assembleUIUrl;
	}
	
	/**
	 * 装配方法
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("assembleItem")
	public String assembleItem(Model model, HttpServletRequest request) {
		
		SfcAssemblyFormMap sfcAssemblyFormMap = getFormMap(SfcAssemblyFormMap.class);
		try{
			workPodPanelService.assembleItem(sfcAssemblyFormMap);
		}catch(BusinessException e){
			return ResponseHelp.responseErrorText(e.getMessage());
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 临时存放参数
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveParam")
	public String saveParam(Model model, HttpServletRequest request){
		String param = request.getParameter("param");
		String data = request.getParameter(param);
		ShiroSecurityHelper.getSession().setAttribute(param, data);
		return ResponseHelp.responseText();
	}
	
	/**
	 * 执行POD工单绑定功能
	 * 
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("podBindShoporder")
	public String podBindShoporder(Model model, HttpServletRequest request) {
		try {
			String shoporderId = request.getParameter("shoporder_id");
			//String shoporderNo = request.getParameter("shoporder_no");
			String sfc = request.getParameter("sfc");
			String wordResourceId = request.getParameter("word_resource_id");
			//String wordFlowId = request.getParameter("wordflow_id");
			String operationId = request.getParameter("operation_id");
			
			if(StringUtils.isEmpty(shoporderId)) {
				throw new BusinessException("请选择要绑定的工单！");
			}
			if(StringUtils.isEmpty(sfc)) {
				throw new BusinessException("请输入要绑定的SFC！");
			}
			if(StringUtils.isEmpty(wordResourceId)) {
				throw new BusinessException("请输入要绑定的资源！");
			}
			//1.sfc不可重复绑定
			String siteId = ShiroSecurityHelper.getSiteId();
			ShopOrderSfcFormMap shopOrderSfcFormMap = new ShopOrderSfcFormMap();
			shopOrderSfcFormMap.put("site_id",siteId);
			shopOrderSfcFormMap.put("sfc",sfc);
			List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByNames(shopOrderSfcFormMap);
			if(ListUtils.isNotNull(listShopOrderSfcFormMap)) {
				throw new BusinessException("SFC编号 "+ sfc +" 已经存在，不可重复绑定！");
			}
			//2.该工单绑定的sfc数量不可超过工单设定的产品数量
			ShoporderFormMap bindSoporderFormMap = new ShoporderFormMap();
			bindSoporderFormMap.put("id",shoporderId);
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByNames(bindSoporderFormMap);
			if(!ListUtils.isNotNull(listShoporderFormMap)) {
				throw new BusinessException("无法找到所选工单的详细信息！");
			}
			bindSoporderFormMap = listShoporderFormMap.get(0);
			
			ShopOrderSfcFormMap shopOrderSfcFormMap2 = new ShopOrderSfcFormMap();
			shopOrderSfcFormMap2.put("site_id",siteId);
			shopOrderSfcFormMap2.put("shoporder_id",shoporderId);
			List<ShopOrderSfcFormMap> listShopOrderSfcFormMap2 = baseMapper.findByNames(shopOrderSfcFormMap2);
			if(ListUtils.isNotNull(listShopOrderSfcFormMap2)) {
				int shoporderNumber = bindSoporderFormMap.getInt("shoporder_number");
				int shoporderSfcNumber = listShopOrderSfcFormMap2.size();
				if(shoporderNumber < shoporderSfcNumber + 1) {
					throw new BusinessException("工单的SFC数量 "+ (shoporderSfcNumber + 1) +" 超过了工单设定的数量"+ shoporderNumber +"！");
				}
			}
			//3.判断输入的操作是否是首操作
			FlowStepFormMap flowStepFormMap = new FlowStepFormMap();
			flowStepFormMap.put("operation_id", operationId);
			flowStepFormMap.put("status", 1);
			List<FlowStepFormMap> listFlowStepFormMap = baseMapper.findByNames(flowStepFormMap);
			if (!ListUtils.isNotNull(listFlowStepFormMap)) {
				throw new BusinessException("操作不是首操作！");
			}
			//4.判断要绑定的工单的工艺路线在所选操作对应的工艺路线(可能多条)中，并且设定选择的工艺路线，以工单为准
			boolean isFlowstepMatched = false;
			FlowStepFormMap bindFistFlowStepFormMap = new FlowStepFormMap();
			String shoporderWorkflowId = bindSoporderFormMap.getStr("process_workflow_id");
			for(FlowStepFormMap map : listFlowStepFormMap) {
				String operationFlowId = map.getStr("process_workflow_id");
				if(operationFlowId.equals(shoporderWorkflowId)) {
					isFlowstepMatched = true;
					bindFistFlowStepFormMap = map;
					break;
				}
			}
			if(!isFlowstepMatched) {
				throw new BusinessException("操作所属的工艺路线和工单的工艺路线不一致，请调整！");
			}
			//5.获取绑定的资源详情
			WorkResourceFormMap bindWorkResourceFormMap = new WorkResourceFormMap();
			bindWorkResourceFormMap.put("id", wordResourceId);
			List<WorkResourceFormMap> listWorkResourceFormMap = baseMapper.findByNames(bindWorkResourceFormMap);
			if(!ListUtils.isNotNull(listWorkResourceFormMap)) {
				throw new BusinessException("无法找到所选资源的详细信息！");
			}
			bindWorkResourceFormMap = listWorkResourceFormMap.get(0);
			String workllineId = bindWorkResourceFormMap.getStr("workline_id");
			if(StringUtils.isEmpty(workllineId)) {
				throw new BusinessException("所选资源没有绑定产线，无法绑定工单！");
			}
			//获取workshopId 
			WorkCenterFormMap workCenterFormMap = new WorkCenterFormMap();
			workCenterFormMap.put("id", workllineId);
			List<WorkCenterFormMap> listWorkCenterFormMap = baseMapper.findByNames(workCenterFormMap);
			workCenterFormMap = listWorkCenterFormMap.get(0);
			String workshopId = workCenterFormMap.getStr("workcenter_parent_id");
			if(StringUtils.isEmpty(workllineId)) {
				throw new BusinessException("所选资源没有绑定车间，无法绑定工单！");
			}
			bindWorkResourceFormMap.put("workshop_id", workshopId);

			workPodPanelService.podBindShoporder(sfc,bindSoporderFormMap,bindFistFlowStepFormMap,bindWorkResourceFormMap);
		} catch (BusinessException e) {
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	@RequestMapping("recordNcCodeMaintenance")
	public String recordNcCodeMaintenance(Model model, HttpServletRequest request){
		
		String dataString = (String) ShiroSecurityHelper.getSession().getAttribute("nccode");
		ShiroSecurityHelper.getSession().removeAttribute("nccode");
		JSONObject dataObj = JSONObject.fromObject(dataString);
		model.addAttribute("ncMap", dataObj);
		return recordNcCodeUrl;
	}
	
	
	/**
	 * 
	 * 0、判断工单状态是否不为：3（已完成）；4（关闭）；5（挂起）
	 * 1、判断是否已经被记录不良（判断shororder_sfc表状态）
	 * 2、向sfc_step表追加上一条记录的完成时间
	 * 3、向sfc_step表添加一条当前操作的完成记录
	 * 4、判断是否找得到下一步的维修操作
	 * 5、向sfc_step表添加下一条维修操作的排队中记录
	 * 6、修改shoporder_sfc表状态为维修中
	 * 7、向mds_sfc_nc表插入一条记录
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("recordNcCode")
	public String recordNcCode(Model model, HttpServletRequest request){
		
		SfcNcFormMap sfcNcFormMap = getFormMap(SfcNcFormMap.class);
		System.out.println(sfcNcFormMap);
		try{
			
			String sfc_step_id = sfcNcFormMap.getStr("sfc_step_id");
			String shoporder_id = sfcNcFormMap.getStr("shoporder_id");
			String operation_id = sfcNcFormMap.getStr("operation_id");
			String process_workflow_id = sfcNcFormMap.getStr("process_workflow_id");
			
			List<SfcStepFormMap> listSfcStepFormMap = baseMapper.findByAttribute("id", sfc_step_id, SfcStepFormMap.class);
			SfcStepFormMap sfcStepFormMap = listSfcStepFormMap.get(0);
			String shoporder_sfc_id = sfcStepFormMap.getStr("shoporder_sfc_id");
			
			List<ShoporderFormMap> listShoporderFormMap = baseMapper.findByAttribute("id", shoporder_id, ShoporderFormMap.class);
			ShoporderFormMap shoporderFormMap = listShoporderFormMap.get(0);
			int shopOrderStatus = shoporderFormMap.getInt("status");
			String shopOrderStatusStr = commonService.getShoporderStatusStr(shopOrderStatus);
			if (shopOrderStatus==3 || shopOrderStatus==4 || shopOrderStatus==5) {
				String msg = "当前工单状态为："+shopOrderStatusStr+", 不允许进行记录不合格操作";
				log.error(msg);
				throw new BusinessException(msg);
			}
			
			// 1 step
			List<ShopOrderSfcFormMap> listshopOrderSfcFormMap = baseMapper.findByAttribute("id", shoporder_sfc_id, ShopOrderSfcFormMap.class);
			ShopOrderSfcFormMap shopOrderSfcFormMap = listshopOrderSfcFormMap.get(0);
			int sfcStatus = shopOrderSfcFormMap.getInt("sfc_status");
			if (sfcStatus==4) {
				String msg = "当前SFC已处于维修中, 不可以进行重复操作";
				log.error(msg);
				throw new BusinessException(msg);
			}
			if (sfcStatus!=1) {
				String msg = "当前SFC不处于生产中，不可以进行该操作";
				log.error(msg);
				throw new BusinessException(msg);
			}
			
			// 2 step
			sfcStepFormMap.put("finish_time", DateUtils.getStringDateTime());
			
			// 3 step
			SfcStepFormMap sfcStepFormMap2 = new SfcStepFormMap();
			sfcStepFormMap2.putAll(sfcStepFormMap);
			sfcStepFormMap2.remove("seq");
			sfcStepFormMap2.put("id", UUIDUtils.getUUID());
			sfcStepFormMap2.put("create_time", DateUtils.getStringDateTime());
			sfcStepFormMap2.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcStepFormMap2.put("status", 2);
			sfcStepFormMap2.put("remark", sfcNcFormMap.getStr("nc_desc"));
			
			// 4 step
			List<FlowStepFormMap> nextOperation = commonService.getNextRepairOperation(operation_id, process_workflow_id);
			if (!ListUtils.isNotNull(nextOperation)) {
				String msg = "下一步骤中未检索到对应的维修操作，请检索工艺路线是否正确";
				log.error(msg);
				throw new BusinessException(msg);
			}
			OperationFormMap operationFormMap2 = null;
			for (FlowStepFormMap flowStepFormMap : nextOperation) {
				String next_operation_id = flowStepFormMap.getStr("next_operation_id");
				List<OperationFormMap> listOperationFormMap = baseMapper.findByAttribute("id", next_operation_id, OperationFormMap.class);
				OperationFormMap operationFormMap = listOperationFormMap.get(0);
				String operationType = operationFormMap.getStr("operation_type");
				if ("repair".equals(operationType)) {
					operationFormMap2 = operationFormMap;
					break;
				}
			}
			if (operationFormMap2==null) {
				String msg = "下一步骤中未检索到对应的维修操作，请检索工艺路线是否正确";
				log.error(msg);
				throw new BusinessException(msg);
			}
			
			// 5 step
			SfcStepFormMap sfcStepFormMap3 = new SfcStepFormMap();
			sfcStepFormMap3.putAll(sfcStepFormMap);
			sfcStepFormMap3.remove("seq");
			sfcStepFormMap3.remove("work_resource_id");
			sfcStepFormMap3.put("id", UUIDUtils.getUUID());
			sfcStepFormMap3.put("create_time", DateUtils.getStringDateTime());
			sfcStepFormMap3.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcStepFormMap3.put("status", 0);
			sfcStepFormMap3.put("operation_id", operationFormMap2.getStr("id"));
			
			// 6 step
			shopOrderSfcFormMap.put("sfc_status", "4");
			workPodPanelService.recordNcCode(sfcNcFormMap, sfcStepFormMap, sfcStepFormMap2, sfcStepFormMap3, shopOrderSfcFormMap);
		}catch(BusinessException e){
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		
		return ResponseHelp.responseText();
	}
	
	/**
	 * 报废界面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("scrap_ui")
	public String scrap_ui(Model model, HttpServletRequest request) {
		
		String dataString = (String) ShiroSecurityHelper.getSession().getAttribute("scrap");
		ShiroSecurityHelper.getSession().removeAttribute("scrap");
		JSONObject dataObj = JSONObject.fromObject(dataString);
		
		SfcNcFormMap sfcNcFormMap = new SfcNcFormMap();
		sfcNcFormMap.put("sfc", dataObj.getString("sfc"));
		sfcNcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		sfcNcFormMap.put("shoporder_id", dataObj.getString("shoporder_id"));
		List<SfcNcFormMap> listSfcNcFormMap = baseMapper.findByNames(sfcNcFormMap);
		SfcNcFormMap sfcNcFormMap2 = listSfcNcFormMap.get(0);
		
		String nc_code_id = sfcNcFormMap2.getStr("nc_code_id");
		String nc_code_group_id = sfcNcFormMap2.getStr("nc_code_group_id");
		
		List<NcCodeFormMap> listNcCodeFormMap = baseMapper.findByAttribute("id", nc_code_id, NcCodeFormMap.class);
		NcCodeFormMap ncCodeFormMap = listNcCodeFormMap.get(0);
		String nc_code = ncCodeFormMap.getStr("nc_code");
		
		List<NcCodeGroupFormMap> listNcCodeGroupFormMap = baseMapper.findByAttribute("id", nc_code_group_id, NcCodeGroupFormMap.class);
		NcCodeGroupFormMap ncCodeGroupFormMap = listNcCodeGroupFormMap.get(0);
		String nc_code_group = ncCodeGroupFormMap.getStr("nc_code_group_no");
		
		sfcNcFormMap2.put("nc_code", nc_code);
		sfcNcFormMap2.put("nc_code_group", nc_code_group);
		model.addAttribute("sfcNcFormMap", sfcNcFormMap2);
		model.addAttribute("assembleMap", dataObj);
		return scrapUrl;
	}
	
	/**
	 * 报废方法
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("podScrap")
	public String podScrap(Model model, HttpServletRequest request) {
		NcRepairFormMap ncRepairFormMap = getFormMap(NcRepairFormMap.class);
		try {
			
			String id = UUIDUtils.getUUID();
			
			//1、向sfc_nc表追加已处置等信息
			SfcNcFormMap sfcNcFormMap = new SfcNcFormMap();
			sfcNcFormMap.put("sfc", ncRepairFormMap.getStr("sfc"));
			sfcNcFormMap.put("status", -1);
			sfcNcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcNcFormMap.put("shoporder_id", ncRepairFormMap.getStr("shoporder_id"));
			List<SfcNcFormMap> listSfcNcFormMap = baseMapper.findByNames(sfcNcFormMap);
			if (!ListUtils.isNotNull(listSfcNcFormMap)) {
				String msg = "未检索到SFC："+ncRepairFormMap.getStr("sfc")+"的不良信息，请确认提交的信息是否无误";
				log.error(msg);
				throw new BusinessException(msg);
			}
			SfcNcFormMap sfcNcFormMap2 = listSfcNcFormMap.get(0);
			sfcNcFormMap2.put("status", "1");
			sfcNcFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcNcFormMap2.put("repair_type", "1");
			sfcNcFormMap2.put("repair_id", id);
			
			//2、新增处置表信息
			ncRepairFormMap.put("id", id);
			ncRepairFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			ncRepairFormMap.put("create_time", DateUtils.getStringDateTime());
			ncRepairFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			
			//3、向sfc_step表最后一条记录追加完成时间
			SfcStepFormMap lastSfcStep = commonService.getLastSfcStep(ncRepairFormMap.getStr("sfc"));
			lastSfcStep.put("finish_time", DateUtils.getStringDateTime());
			
			//4、向sfc_step表追加一条完成记录，备注为报废
			SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
			sfcStepFormMap.putAll(lastSfcStep);
			sfcStepFormMap.remove("seq");
			sfcStepFormMap.put("id", UUIDUtils.getUUID());
			sfcStepFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcStepFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcStepFormMap.put("create_time", DateUtils.getStringDateTime());
			sfcStepFormMap.put("status", 2);
			sfcStepFormMap.put("remark", ncRepairFormMap.getStr("repair_desc"));
			
			//5、修改shoporder_sfc表的sfc状态为报废
			String shopOrderSfcId = sfcStepFormMap.getStr("shoporder_sfc_id");
			List<ShopOrderSfcFormMap> listShopOrderSfcFormMap = baseMapper.findByAttribute("id", shopOrderSfcId, ShopOrderSfcFormMap.class);
			ShopOrderSfcFormMap shopOrderSfcFormMap = listShopOrderSfcFormMap.get(0);
			shopOrderSfcFormMap.put("sfc_status", 3);
			
			//6、判断当前SFC是否为工单的最后一个SFC
			ShoporderFormMap lastSfcOnShoporder = commonService.isLastSfcOnShoporder(ncRepairFormMap.getStr("shoporder_id"));
			
			workPodPanelService.podScrap(sfcNcFormMap2, ncRepairFormMap, lastSfcStep, sfcStepFormMap, shopOrderSfcFormMap, lastSfcOnShoporder);
		}catch(BusinessException e) {
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		return ResponseHelp.responseText();
	}
	
	/**
	 * 维修界面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("repair_ui")
	public String repair_ui(Model model, HttpServletRequest request) {
		
		String dataString = (String) ShiroSecurityHelper.getSession().getAttribute("repair");
		ShiroSecurityHelper.getSession().removeAttribute("repair");
		JSONObject dataObj = JSONObject.fromObject(dataString);
		
		String operation_id = dataObj.getString("operation_id");
		String process_workflow_id = dataObj.getString("process_workflow_id");
		
		SfcNcFormMap sfcNcFormMap = new SfcNcFormMap();
		sfcNcFormMap.put("sfc", dataObj.getString("sfc"));
		sfcNcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
		sfcNcFormMap.put("shoporder_id", dataObj.getString("shoporder_id"));
		List<SfcNcFormMap> listSfcNcFormMap = baseMapper.findByNames(sfcNcFormMap);
		SfcNcFormMap sfcNcFormMap2 = listSfcNcFormMap.get(0);
		
		String nc_code_id = sfcNcFormMap2.getStr("nc_code_id");
		String nc_code_group_id = sfcNcFormMap2.getStr("nc_code_group_id");
		
		List<NcCodeFormMap> listNcCodeFormMap = baseMapper.findByAttribute("id", nc_code_id, NcCodeFormMap.class);
		NcCodeFormMap ncCodeFormMap = listNcCodeFormMap.get(0);
		String nc_code = ncCodeFormMap.getStr("nc_code");
		
		List<NcCodeGroupFormMap> listNcCodeGroupFormMap = baseMapper.findByAttribute("id", nc_code_group_id, NcCodeGroupFormMap.class);
		NcCodeGroupFormMap ncCodeGroupFormMap = listNcCodeGroupFormMap.get(0);
		String nc_code_group = ncCodeGroupFormMap.getStr("nc_code_group_no");
		
		//查找下一步操作
		List<FlowStepFormMap> nextOperation = commonService.getNextOperation(operation_id, process_workflow_id);
		if (ListUtils.isNotNull(nextOperation)) {
			for (FlowStepFormMap flowStepFormMap : nextOperation) {
				FlowStepFormMap flowStepFormMap2 = nextOperation.get(0);
				String next_operation_id = flowStepFormMap2.getStr("next_operation_id");
				List<OperationFormMap> listOperationFormMap = baseMapper.findByAttribute("id", next_operation_id, OperationFormMap.class);
				OperationFormMap operationFormMap = listOperationFormMap.get(0);
				String operation_no = operationFormMap.getStr("operation_no");
				flowStepFormMap.put("operation_no", operation_no);
			}
			model.addAttribute("nextOperations", nextOperation);
		}
		
		
		sfcNcFormMap2.put("nc_code", nc_code);
		sfcNcFormMap2.put("nc_code_group", nc_code_group);
		model.addAttribute("sfcNcFormMap", sfcNcFormMap2);
		model.addAttribute("assembleMap", dataObj);
		return repairUrl;
	}
	
	/**
	 * 维修方法
	 * 1、向sfc_nc表追加已处置等信息
	 * 2、新增处置表信息
	 * 3、向sfc_step表最后一条记录追加完成时间
	 * 4、向sfc_step表追加一条完成记录，备注为已维修
	 * 5、向sfc_step表添加一条新记录
	 * @param model
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("podRepair")
	public String podRepair(Model model, HttpServletRequest request) {
		
		NcRepairFormMap ncRepairFormMap = getFormMap(NcRepairFormMap.class);
		
		try {
			String id = UUIDUtils.getUUID();
			
			//1、向sfc_nc表追加已处置等信息
			SfcNcFormMap sfcNcFormMap = new SfcNcFormMap();
			sfcNcFormMap.put("sfc", ncRepairFormMap.getStr("sfc"));
			sfcNcFormMap.put("status", -1);
			sfcNcFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcNcFormMap.put("shoporder_id", ncRepairFormMap.getStr("shoporder_id"));
			List<SfcNcFormMap> listSfcNcFormMap = baseMapper.findByNames(sfcNcFormMap);
			if (!ListUtils.isNotNull(listSfcNcFormMap)) {
				String msg = "未检索到SFC："+ncRepairFormMap.getStr("sfc")+"的不良信息，请确认提交的信息是否无误";
				log.error(msg);
				throw new BusinessException(msg);
			}
			SfcNcFormMap sfcNcFormMap2 = listSfcNcFormMap.get(0);
			sfcNcFormMap2.put("status", "1");
			sfcNcFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcNcFormMap2.put("repair_type", "1");
			sfcNcFormMap2.put("repair_id", id);
			
			//2、新增处置表信息
			ncRepairFormMap.put("id", id);
			ncRepairFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			ncRepairFormMap.put("create_time", DateUtils.getStringDateTime());
			ncRepairFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			
			//3、向sfc_step表最后一条记录追加完成时间
			SfcStepFormMap lastSfcStep = commonService.getLastSfcStep(ncRepairFormMap.getStr("sfc"));
			lastSfcStep.put("finish_time", DateUtils.getStringDateTime());
			
			//4、向sfc_step表追加一条完成记录，备注为报废
			SfcStepFormMap sfcStepFormMap = new SfcStepFormMap();
			sfcStepFormMap.putAll(lastSfcStep);
			sfcStepFormMap.remove("seq");
			sfcStepFormMap.put("id", UUIDUtils.getUUID());
			sfcStepFormMap.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcStepFormMap.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcStepFormMap.put("create_time", DateUtils.getStringDateTime());
			sfcStepFormMap.put("remark", ncRepairFormMap.getStr("repair_desc"));
			sfcStepFormMap.put("status", 2);
			
			//5、向sfc_step表添加一条下一步骤的记录
			SfcStepFormMap sfcStepFormMap2 = new SfcStepFormMap();
			sfcStepFormMap2.putAll(lastSfcStep);
			sfcStepFormMap2.remove("seq");
			sfcStepFormMap2.remove("work_resource_id");
			sfcStepFormMap2.put("id", UUIDUtils.getUUID());
			sfcStepFormMap2.put("operation_id", ncRepairFormMap.getStr("next_operation"));
			sfcStepFormMap2.put("site_id", ShiroSecurityHelper.getSiteId());
			sfcStepFormMap2.put("create_user", ShiroSecurityHelper.getCurrentUsername());
			sfcStepFormMap2.put("create_time", DateUtils.getStringDateTime());
			sfcStepFormMap2.put("status", 0);

			workPodPanelService.podRepair(sfcNcFormMap2, ncRepairFormMap, lastSfcStep, sfcStepFormMap, sfcStepFormMap2);
		}catch(BusinessException e) {
			String msg = e.getMessage();
			log.error(msg);
			return ResponseHelp.responseErrorText(msg);
		}
		
		return ResponseHelp.responseText();
	}
}
